package com.zhehekeji.opsys.api.plugin.wechat.util;

import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * @ClassName XmlUtils
 * @Description TODO
 * @author chenweiliu chenwei.liu@163.com
 * @date 2017-4-24   下午1:51:03
 */
public class XmlUtils {
	
	public static Map<String, String> xmlToMap(HttpServletRequest request) throws Exception{
        Map<String, String> map = new HashMap<String, String>();
        SAXReader reader = new SAXReader();
        
        InputStream in = null;
        try{
        	in = request.getInputStream();
        	Document doc = reader.read(in);
        	Element root = doc.getRootElement();
        	@SuppressWarnings("unchecked")
        	List<Element> list = root.elements();
        	for (Element e : list) {
        		map.put(e.getName(), e.getText());
        	}
        }finally{
        	if (in != null){
        		in.close();
        		in = null;
        	}
        }
        return map;
    }
	
	public static Object xmlToObject(String xml, Class<?> clazz) throws JAXBException {
		JAXBContext jc = JAXBContext.newInstance(clazz); 
    	Unmarshaller unmarshaller = jc.createUnmarshaller();  
        StringReader sr = new StringReader(xml);  
        Object object = unmarshaller.unmarshal(sr);
        return object;
    }
	

	public static String ObjectToXml(Object obj) throws JAXBException{
		JAXBContext jc = JAXBContext.newInstance(obj.getClass());  
	    Marshaller marshaller = jc.createMarshaller();
	    //决定是否在转换成xml时同时进行格式化（即按标签自动换行，否则即是一行的xml）
	    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
	    //Marshaller.JAXB_ENCODING xml的编码方式
	    marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");
	    //省略头信息 
	    marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
	    StringWriter writer = new StringWriter(); 
	    marshaller.marshal(obj, writer); 
	    return writer.toString();
	}
	
	/*public static void main(String[] args) throws JAXBException {
		TextRsp rsp = new TextRsp();
		rsp.setContent("已收到您的反馈，稍候我们会联系您，O(∩_∩)O谢谢您的支持！");
		rsp.setCreateTime(System.currentTimeMillis());
		rsp.setFromUserName("fromUser");
		rsp.setToUserName("toUser");
		System.out.println(ObjectToXml(rsp));
	}*/
}

